<template>
    <el-upload
        :action="''"
        name='file'
        :before-upload='beforeUpload'
        :http-request='uploadHandle'
        :show-file-list="false">
        <!-- 多选 -->
        <template v-if="multiple">
            <div class="upload-list f-s" >
                <template v-if="result && result.length">
                    <div v-for="item in result" :key='item' class="img-wrapper" :style="wrapperStyle">
                        <el-image :src="`${IMG_HOST}${item}`" fit='cover'></el-image>
                        <div class="mask" @click.stop='deleteItem(item)' :style="{lineHeight: width + 'px'}">
                            <i class="el-icon-delete"></i>
                        </div>
                    </div>
                </template>
                
                <div class="select-file" :style="wrapperStyle">
                    <i class="el-icon-plus"></i>
                </div>
            </div>
        </template>
        <!-- 单选 -->
        <template v-else>
            <!-- 图片类上传 -->
            <template v-if="fileType == 'IMAGE'">
                <div class="img-wrapper" v-if="result" :style="wrapperStyle" style="margin-bottom:0">
                    <el-image :src="`${IMG_HOST}${result}`" fit='cover'></el-image>
                </div>
                <div class="select-file" v-else :style="wrapperStyle">
                    <i class="el-icon-plus"></i>
                </div>
            </template>
            <!-- 文件上传 -->
            <template v-else>
                <span v-if="result">{{result}}</span>
                <el-button type='primary' v-else>上传文件</el-button>
            </template>
        </template>
    </el-upload>
</template>

<script>
    import {toast} from '@u';
    import { DEFAULT_IMG_UPLOAD_DIR_ID, IMG_UPLOAD_SIZE_LIMIT} from '@const';
    import { Loading } from 'element-ui';
    export default {
        props : {
            value : {
                type : String | Array,
                default : null
            },
            //是否多选
            multiple : {
                type : Boolean,
                default : false
            },
            //文件类型
			fileType :{
				type : String,
				default : 'IMAGE'
			},
            //图片显示宽度
            width : {
                type : Number,
                default : 108
            }
        },
        watch : {
            value : {
                handler : function (n) {
                    if (!n) {
                        this.result = this.multiple ? [] : '';
                    } else {
                        this.result = n;
                    }
                },
                immediate : true
            }
        },
        data () {
            return {
                result : []
            }
        },
        computed: {
			accept () {
				if (this.fileType == 'IMAGE') {
					return '.jpg,.png,.JPG,.PNG'
				} 
			},
            wrapperStyle () {
                return {
                    width : `${this.width}px`,
                    height : `${this.width}px`,
                    lineHeight : `${this.width}px`,
                }
            }
		},
        methods : {
            beforeUpload (file) {
                if (this.fileType == 'IMAGE') {
                    const isLt400kb = file.size / 1024 / 1024 < IMG_UPLOAD_SIZE_LIMIT;
                    if (!isLt400kb) {
                        toast('上传图片不得大于400kb', 'error')
                        return isLt400kb
                    }
                    return true;
                }
                return true;
            },
            uploadHandle (file) {
                let formData = new FormData();
                formData.append('file', file.file);
                formData.append('file_type', this.fileType);
                formData.append('directory_id', DEFAULT_IMG_UPLOAD_DIR_ID);

                let loadingInstance = Loading.service({
					fullscreen :true,
					lock :true,
					text : '上传中'
				});

                this.__api.common.upload(formData).then(res => {
                    this.result = this.multiple ? [...this.result, res.filename] : res.filename;
                    loadingInstance.close();

                    this.$emit('input', this.result);

                    //如果是单选，则向外emit一个change事件
                    if (!this.multiple) {
                        this.$emit('change', this.result)
                    }
                }).catch(_ => {
                    loadingInstance.close();
                })

            },
            //删除图片 -> 仅在多选时会触发
            deleteItem (item) {
                if (this.multiple) {
                    this.result = this.result.filter(v => v != item);
                } else {
                    this.result = null;
                }
                this.$emit('input', this.result);
            }
        }
    }
</script>

<style lang='less' scoped>
    .select-file {
        background-color: #fbfdff;
        border: 1px dashed #c0ccda;
        border-radius: 6px;
        box-sizing: border-box;
        width: 108px;
        height: 108px;
        cursor: pointer;
        line-height: 106px;
        vertical-align: top;
    }
    .img-wrapper {
        width: 108px;
        height: 108px;
        margin-right: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
        .el-image {
            width: 100%;
            height: 100%;
        }
        .mask {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
            background: rgba(0, 0, 0, .6);
            width: 100%;
            height: 100%;
            line-height: 108px;
            color: #fff;
        }
    }
    .img-wrapper {
        &:hover {
            .mask {
                display: block;
            }
        }
    }
    .upload-list {
        flex-wrap : wrap;
    }
</style>